//package com.wbk.lotterysystemgateway.filter;
//
//import com.coolgua.config.CoolguaConfig;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.codec.binary.Hex;
//import org.apache.commons.codec.digest.DigestUtils;
//import org.apache.http.HttpHeaders;
//import org.apache.http.HttpResponse;
//import org.apache.http.NameValuePair;
//import org.apache.http.client.methods.RequestBuilder;
//import org.apache.http.client.utils.URLEncodedUtils;
//import org.apache.http.conn.ssl.DefaultHostnameVerifier;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.message.BasicNameValuePair;
//import org.apache.http.ssl.SSLContextBuilder;
//import org.apache.http.util.EntityUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.nio.charset.Charset;
//import java.text.SimpleDateFormat;
//import java.util.*;
//
///*******************************************************************************
// * @project: competition
// * @package: com.coolgua.common.util
// * @author: wbk
// * @created: 2021/4/27
// * @purpose:
// ******************************************************************************/
//@Slf4j
//@Component
//public class HuaWeiCloudUtil {
//
//    @Autowired
//    CoolguaConfig coolguaConfig;
//
//    //无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
//    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
//    //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
//    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";
//
//    public void sendSms(String mobilePhone, String random) {
//        //必填,全局号码格式(包含国家码),示例:+86151****6789,多个号码之间用英文逗号分隔
//        String receiver = "+86" + mobilePhone; //短信接收人号码
//        //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
//        String statusCallBack = "";
//        /**
//         * 选填,使用无变量模板时请赋空值 String templateParas = "";
//         * 单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为"[\"369751\"]"
//         * 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
//         * 模板中的每个变量都必须赋值，且取值不能为空
//         * 查看更多模板和变量规范:产品介绍>模板和变量规范
//         */
//        String templateParas = "[\"" + random + "\"]"; //模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）。
//        //请求Body,不携带签名名称时,signature请填null
//        String body = buildRequestBody(coolguaConfig.getHuaWeiCloud().getSender(), receiver, coolguaConfig.getHuaWeiCloud().getTemplateCode().get(1), templateParas, statusCallBack, coolguaConfig.getHuaWeiCloud().getSignature());
//        if (null == body || body.isEmpty()) {
//            log.error("body is null.");
//            return;
//        }
//        //请求Headers中的X-WSSE参数值
//        String wsseHeader = buildWsseHeader(coolguaConfig.getHuaWeiCloud().getAppKey(), coolguaConfig.getHuaWeiCloud().getAppSecret());
//        if (null == wsseHeader || wsseHeader.isEmpty()) {
//            log.error("wsse header is null.");
//            return;
//        }
//        CloseableHttpClient client = null;
//        try {
//            client = HttpClients.custom()
//                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
//                            (x509CertChain, authType) -> true).build())
//                    .setSSLHostnameVerifier(new DefaultHostnameVerifier())
//                    .build();
//            HttpResponse response = client.execute(RequestBuilder.create("POST")//请求方法POST
//                    .setUri("https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1")
//                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
//                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
//                    .addHeader("X-WSSE", wsseHeader)
//                    .setEntity(new StringEntity(body)).build());
//            log.info(EntityUtils.toString(response.getEntity())); //打印响应消息实体
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        }
//    }
//
//    /**
//     * 构造请求Body体
//     *
//     * @param sender
//     * @param receiver
//     * @param templateId
//     * @param templateParas
//     * @param statusCallbackUrl
//     * @param signature         | 签名名称,使用国内短信通用模板时填写
//     * @return
//     */
//    static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
//                                   String statusCallbackUrl, String signature) {
//        if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
//                || templateId.isEmpty()) {
//            log.error("buildRequestBody(): sender, receiver or templateId is null.");
//            return null;
//        }
//        List<NameValuePair> keyValues = new ArrayList<NameValuePair>();
//        keyValues.add(new BasicNameValuePair("from", sender));
//        keyValues.add(new BasicNameValuePair("to", receiver));
//        keyValues.add(new BasicNameValuePair("templateId", templateId));
//        if (null != templateParas && !templateParas.isEmpty()) {
//            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
//        }
//        if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
//            keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
//        }
//        if (null != signature && !signature.isEmpty()) {
//            keyValues.add(new BasicNameValuePair("signature", signature));
//        }
//        return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
//    }
//
//    /**
//     * 构造X-WSSE参数值
//     *
//     * @param appKey
//     * @param appSecret
//     * @return
//     */
//    static String buildWsseHeader(String appKey, String appSecret) {
//        if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
//            log.error("buildWsseHeader(): appKey or appSecret is null.");
//            return null;
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//        String time = sdf.format(new Date()); //Created
//        String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce
//        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
//        String hexDigest = Hex.encodeHexString(passwordDigest);
//        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest
//        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
//    }
//}
